<template>
  <div class="admin-meal">
    <div class="header">
      <h2>餐饮记录管理</h2>
      <el-button type="primary" @click="handleAdd">新增餐饮记录</el-button>
    </div>

    <!-- 搜索和筛选 -->
    <div class="filter-container">
      <el-form :inline="true" :model="queryParams">
        <el-form-item label="老人姓名">
          <el-input
            v-model="queryParams.elderName"
            placeholder="请输入老人姓名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="餐饮类型">
          <el-select
            v-model="queryParams.mealType"
            placeholder="请选择餐饮类型"
            clearable
            style="width: 200px"
          >
            <el-option label="早餐" value="早餐" />
            <el-option label="午餐" value="午餐" />
            <el-option label="晚餐" value="晚餐" />
            <el-option label="加餐" value="加餐" />
          </el-select>
        </el-form-item>
        <el-form-item label="日期范围">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <el-table
      :data="mealList"
      v-loading="tableLoading"
      style="width: 100%"
      border
    >
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column prop="recordId" label="记录ID" width="100" align="center" />
      <el-table-column prop="elderName" label="老人姓名" width="120" align="center" />
      <el-table-column prop="mealType" label="餐饮类型" width="100" align="center" />
      <el-table-column prop="mealDate" label="用餐日期" width="120" align="center">
        <template #default="{ row }">
          {{ formatDate(row.mealDate) }}
        </template>
      </el-table-column>
      <el-table-column prop="mealTime" label="用餐时间" width="100" align="center" />
      <el-table-column prop="foodContent" label="食物内容" min-width="200">
        <template #default="{ row }">
          <el-tooltip :content="row.foodContent" placement="top">
            <span class="text-truncate">{{ row.foodContent }}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="intakeAmount" label="摄入量" width="100" align="center">
        <template #default="{ row }">
          {{ row.intakeAmount }}克
        </template>
      </el-table-column>
      <el-table-column prop="caregiverName" label="记录护工" width="120" align="center" />
      <el-table-column prop="status" label="状态" width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="row.status === 'active' ? 'success' : 'info'">
            {{ row.status === 'active' ? '有效' : '失效' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" align="center" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button type="warning" size="small" @click="handleStatus(row)">
            {{ row.status === 'active' ? '设为失效' : '设为有效' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      :before-close="handleClose"
    >
      <el-form
        ref="mealFormRef"
        :model="mealForm"
        :rules="mealRules"
        label-width="100px"
      >
        <el-form-item label="老人" prop="elderId">
          <el-select v-model="mealForm.elderId" placeholder="请选择老人" style="width: 100%">
            <el-option
              v-for="elder in elders"
              :key="elder.elderId"
              :label="elder.name"
              :value="elder.elderId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="餐饮类型" prop="mealType">
          <el-select v-model="mealForm.mealType" placeholder="请选择餐饮类型" style="width: 100%">
            <el-option label="早餐" value="早餐" />
            <el-option label="午餐" value="午餐" />
            <el-option label="晚餐" value="晚餐" />
            <el-option label="加餐" value="加餐" />
          </el-select>
        </el-form-item>
        <el-form-item label="用餐日期" prop="mealDate">
          <el-date-picker
            v-model="mealForm.mealDate"
            type="date"
            placeholder="请选择用餐日期"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="用餐时间" prop="mealTime">
          <el-time-picker
            v-model="mealForm.mealTime"
            placeholder="请选择用餐时间"
            value-format="HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="食物内容" prop="foodContent">
          <el-input
            v-model="mealForm.foodContent"
            type="textarea"
            :rows="3"
            placeholder="请输入食物内容"
          />
        </el-form-item>
        <el-form-item label="摄入量" prop="intakeAmount">
          <el-input-number
            v-model="mealForm.intakeAmount"
            :min="0"
            :max="1000"
            controls-position="right"
            style="width: 100%"
          />
          <span style="margin-left: 10px; color: #666">克</span>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="mealForm.remark"
            type="textarea"
            :rows="2"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { mealApi } from '@/api/meal'
import { elderApi } from '@/api/elder'

// 响应式数据
const tableLoading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const mealList = ref([])
const elders = ref([])
const total = ref(0)
const dateRange = ref([])

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  elderName: '',
  mealType: '',
  startDate: '',
  endDate: ''
})

const mealForm = reactive({
  recordId: '',
  elderId: '',
  mealType: '',
  mealDate: '',
  mealTime: '',
  foodContent: '',
  intakeAmount: 0,
  remark: ''
})

const mealRules = {
  elderId: [{ required: true, message: '请选择老人', trigger: 'change' }],
  mealType: [{ required: true, message: '请选择餐饮类型', trigger: 'change' }],
  mealDate: [{ required: true, message: '请选择用餐日期', trigger: 'change' }],
  mealTime: [{ required: true, message: '请选择用餐时间', trigger: 'change' }],
  foodContent: [{ required: true, message: '请输入食物内容', trigger: 'blur' }],
  intakeAmount: [{ required: true, message: '请输入摄入量', trigger: 'blur' }]
}

const mealFormRef = ref()

// 计算属性
const computedQueryParams = computed(() => {
  const params = { ...queryParams }
  if (dateRange.value && dateRange.value.length === 2) {
    params.startDate = dateRange.value[0]
    params.endDate = dateRange.value[1]
  } else {
    params.startDate = ''
    params.endDate = ''
  }
  return params
})

// 方法
const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString('zh-CN')
}

const loadMeals = async () => {
  tableLoading.value = true
  try {
    const response = await mealApi.getMeals(computedQueryParams.value)
    mealList.value = response.data.list || []
    total.value = response.data.total || 0
  } catch (error) {
    ElMessage.error('加载餐饮记录失败')
    console.error('加载餐饮记录失败:', error)
  } finally {
    tableLoading.value = false
  }
}

const loadElders = async () => {
  try {
    const response = await elderApi.getElders({ pageNum: 1, pageSize: 1000 })
    elders.value = response.data.list || []
  } catch (error) {
    console.error('加载老人列表失败:', error)
  }
}

const handleSearch = () => {
  queryParams.pageNum = 1
  loadMeals()
}

const handleReset = () => {
  Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 10,
    elderName: '',
    mealType: '',
    startDate: '',
    endDate: ''
  })
  dateRange.value = []
  loadMeals()
}

const handleSizeChange = (val) => {
  queryParams.pageSize = val
  queryParams.pageNum = 1
  loadMeals()
}

const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  loadMeals()
}

const handleAdd = () => {
  dialogTitle.value = '新增餐饮记录'
  Object.assign(mealForm, {
    recordId: '',
    elderId: '',
    mealType: '',
    mealDate: new Date().toISOString().split('T')[0],
    mealTime: '12:00:00',
    foodContent: '',
    intakeAmount: 0,
    remark: ''
  })
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogTitle.value = '编辑餐饮记录'
  Object.assign(mealForm, { ...row })
  dialogVisible.value = true
}

const handleStatus = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要${row.status === 'active' ? '设为失效' : '设为有效'}吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const newStatus = row.status === 'active' ? 'inactive' : 'active'
    await mealApi.updateMealStatus(row.recordId, newStatus)
    ElMessage.success('操作成功')
    loadMeals()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

const handleClose = () => {
  dialogVisible.value = false
  mealFormRef.value?.resetFields()
}

const handleSubmit = async () => {
  if (!mealFormRef.value) return
  
  try {
    await mealFormRef.value.validate()
    
    if (dialogTitle.value === '新增餐饮记录') {
      await mealApi.addMeal(mealForm)
      ElMessage.success('新增成功')
    } else {
      await mealApi.updateMeal(mealForm)
      ElMessage.success('更新成功')
    }
    
    dialogVisible.value = false
    loadMeals()
  } catch (error) {
    if (error.errors) {
      ElMessage.error('请完善表单信息')
    } else {
      ElMessage.error('操作失败')
    }
  }
}

// 生命周期
onMounted(() => {
  loadMeals()
  loadElders()
})
</script>

<style scoped>
.admin-meal {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filter-container {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.text-truncate {
  display: inline-block;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
